//
//  WHYRefreshControl.swift
//  WHYWeibo-1.0
//
//  Created by 王洪运 on 15/11/28.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit

private let WHYRefreshControlOffset: CGFloat = -60

class WHYRefreshControl: UIRefreshControl {

//    MARK: - 构造函数
    override init() {
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    private lazy var refreshView: WHYRefreshView = WHYRefreshView.refreshView()
    
    private func setupUI () {
        
        tintColor = UIColor.clearColor()
        
        addSubview(refreshView)
        
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
            make.size.equalTo(refreshView.bounds.size)
        }
        
//        让监听方法在主线程没有任务时再执行
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
    
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    

    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
//        当刷新界面存在时，直接返回，不做任何操作
        if frame.origin.y > 0 { return }
        
//        当正在刷新数据时，直接返回，不做任何操作
        if refreshing {
            refreshView.startAnimation()
            return
        }
        
        if frame.origin.y < WHYRefreshControlOffset && !refreshView.rotateFlag {
            refreshView.rotateFlag = true
        }else if frame.origin.y > WHYRefreshControlOffset && refreshView.rotateFlag {
            refreshView.rotateFlag = false
        }
        
    }
    
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.startAnimation()
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopAnimation()
    }
    
}

class WHYRefreshView: UIView {
    
    /// 箭头旋转标记  -- 默认是向下的
    private var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
    }
    
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipIconImage: UIImageView!
    @IBOutlet weak var loadingIconView: UIImageView!

    
    class func refreshView () -> WHYRefreshView {
        let nib = UINib(nibName: "WHYRefreshView", bundle: nil)
        return nib.instantiateWithOwner(nil, options: nil).last as! WHYRefreshView
    }
    
    private func rotateTipIcon () {
        
//系统默认的旋转方向是顺时针的，并且遵循就近原则
//所以需要对旋转的角度进行改变，
//当此函数的调用次数为奇数次时，rotateFlag是true，箭头开始时是向下的
//        此时angle的值小于180°，那么箭头会顺时针旋转angle°，旋转完成后箭头向上
 //当此函数的调用偶数为奇数次时，rotateFlag是false，箭头开始时向上的
//        此时angle的值大于180°，那么箭头顺时针旋转时会旋转大于180°，而箭头逆时针旋转时会旋转小于180°，根据就近原则，此时箭头会逆时针旋转，旋转完成后箭头向下
        var angle = CGFloat(M_PI)
        angle += rotateFlag ? -0.00000000001 : 0.00000000001
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIconImage.transform = CGAffineTransformRotate(self.tipIconImage.transform, angle)
        }
    }
    
    private func startAnimation () {
        
        let key = "transform.rotation"
        
        if let _ = loadingIconView.layer.animationForKey(key) {
            return
        }
        
        tipView.hidden = true
        
        let anmi = CABasicAnimation(keyPath: key)
        anmi.duration = 20
        anmi.toValue = 2 * M_PI
        anmi.repeatCount = MAXFLOAT
        
        loadingIconView.layer.addAnimation(anmi, forKey: nil)
        
    }
    
    private func stopAnimation () {
        tipView.hidden = false
        loadingIconView.layer.removeAllAnimations()
    }
    
    
    
}













